// patient dashboard
// dev: http://tcga.github.com/?module=https://dl.dropbox.com/s/y6u2mrmfw9avzmt/pdash.js?dl=1
// prod: http://tcga.github.com/?module=http://tcgapps.googlecode.com/git/pdash.js

console.log('patient dashboard');

pdash={
	
	data:{	// data folder
		patient:[]
	},
	
	load:function(url,cb,er){ // load script / JSON
		var s = document.createElement('script');
		s.src=url;
		s.id = 'UID'+Math.random().toString().slice(2);
		if(!!cb){s.onload=cb}
		if(!!er){s.onerror=er}
		document.body.appendChild(s);
		setTimeout('document.body.removeChild(document.getElementById("'+s.id+'"));',3000); // is the waiting still needed ?
		return s.id
	},
	
	start:function(){		// Register module and move to new tab
		TCGA.ui.registerTab({
			id:'pdash',
			title:'Patient Dashboard',
			switchTab:true,
			content:'<div id=pdashMsg>Loading patient files</div><hr><div id=pdashContent></div>'});
		// Does some annoying things to TCGA
		//TCGA.sparql = TCGA.find;
		
		// Loads external libraries
		//TCGA.loadScript('https://jmat.googlecode.com/git/jmat.js', function(){pdash.getPatients()});  // production
		//TCGA.loadScript('https://dl.dropbox.com/s/y6u2mrmfw9avzmt/pdash.js', function(){pdash.getPatients()});  // production
		
		this.load('https://dl-web.dropbox.com/get/http/jmat/jmat.js?w=1ad340b9', function(){pdash.getPatients()});  // development
	},
	
	msg:function(html,color){ // displays msg in the mesage div
		if(!color){color='blue'};
		$('#pdashMsg').html(html);
		$('#pdashMsg').css('color',color);
	},
	
	getPatients:function(){
		/*
		Results obtained by running

		TCGA.get.sparql("http://agalpha.mathbiol.org/repositories/tcga?infer=true&query=prefix%20tcga%3A%3Chttp%3A%2F%2Fpurl.org%2Ftcga%2Fcore%23%3E%20select%20%3FdiseaseStudyName%20%3Furl%20where%20%7B%20%3Ffile%20rdf%3Atype%20tcga%3AFile%20.%20%20%3Ffile%20rdfs%3Alabel%20%3FfileName%20.%20%20filter%20contains(%3FfileName%2C%20%22clinical_patient%22)%20%3Ffile%20tcga%3AdiseaseStudy%20%3FdiseaseStudy%20.%20%20%3FdiseaseStudy%20rdfs%3Alabel%20%3FdiseaseStudyName%20.%20%20%3Ffile%20tcga%3AcenterDomain%20%3FcenterDomain%20.%20%20%3FcenterDomain%20rdfs%3Alabel%20%22biotab%22%20.%20%20%3Ffile%20tcga%3Aurl%20%3Furl%20.%20%20%7D",function(err,res){sparqlResults = res;console.log('done')})

		*/

		var res = {"head":{"vars":["diseaseStudyName","url"]},"results":{"bindings":[{"diseaseStudyName":{"type":"literal","value":"gbm"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/gbm/bcr/biotab/clin/clinical_patient_gbm.txt"}},{"diseaseStudyName":{"type":"literal","value":"ov"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/ov/bcr/biotab/clin/clinical_patient_ov.txt"}},{"diseaseStudyName":{"type":"literal","value":"coad"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/coad/bcr/biotab/clin/clinical_patient_coad.txt"}},{"diseaseStudyName":{"type":"literal","value":"lusc"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lusc/bcr/biotab/clin/clinical_patient_lusc.txt"}},{"diseaseStudyName":{"type":"literal","value":"luad"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/luad/bcr/biotab/clin/clinical_patient_luad.txt"}},{"diseaseStudyName":{"type":"literal","value":"kirp"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/kirp/bcr/biotab/clin/clinical_patient_kirp.txt"}},{"diseaseStudyName":{"type":"literal","value":"ucec"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/ucec/bcr/biotab/clin/clinical_patient_ucec.txt"}},{"diseaseStudyName":{"type":"literal","value":"read"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/read/bcr/biotab/clin/clinical_patient_read.txt"}},{"diseaseStudyName":{"type":"literal","value":"lihc"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lihc/bcr/biotab/clin/clinical_patient_lihc.txt"}},{"diseaseStudyName":{"type":"literal","value":"skcm"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/skcm/bcr/biotab/clin/clinical_patient_skcm.txt"}},{"diseaseStudyName":{"type":"literal","value":"cesc"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/cesc/bcr/biotab/clin/clinical_patient_cesc.txt"}},{"diseaseStudyName":{"type":"literal","value":"laml"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/laml/bcr/biotab/clin/clinical_patient_laml.txt"}},{"diseaseStudyName":{"type":"literal","value":"prad"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/prad/bcr/biotab/clin/clinical_patient_prad.txt"}},{"diseaseStudyName":{"type":"literal","value":"hnsc"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/hnsc/bcr/biotab/clin/clinical_patient_hnsc.txt"}},{"diseaseStudyName":{"type":"literal","value":"thca"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/thca/bcr/biotab/clin/clinical_patient_thca.txt"}},{"diseaseStudyName":{"type":"literal","value":"blca"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/blca/bcr/biotab/clin/clinical_patient_blca.txt"}},{"diseaseStudyName":{"type":"literal","value":"kirc"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/kirc/bcr/biotab/clin/clinical_patient_kirc.txt"}},{"diseaseStudyName":{"type":"literal","value":"stad"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/stad/bcr/biotab/clin/clinical_patient_stad.txt"}},{"diseaseStudyName":{"type":"literal","value":"lgg"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lgg/bcr/biotab/clin/clinical_patient_lgg.txt"}},{"diseaseStudyName":{"type":"literal","value":"brca"},"url":{"type":"literal","value":"https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/brca/bcr/biotab/clin/clinical_patient_brca.txt"}}]}};
	pdash.data.patientTablesUrls=res.results.bindings.map(function(xi){return xi.url.value});
	//console.log('... '+pdash.data.patientTablesUrls.length+' Patient Tables found');
	pdash.msg('... '+pdash.data.patientTablesUrls.length+' Patient Tables found, loading them ...','green');
	//TCGA.ui.toast.success('... '+pdash.data.patientTablesUrls.length+' Patient Tables found')
	// Process patient tables:
	var count = 0, n = pdash.data.patientTablesUrls.length;
	pdash.data.patientTablesUrls.map(function(xi,i){
		var url = pdash.data.patientTablesUrls[i];
		jQuery.get(url,function(x){
			pdash.data.patient[i]=jmat.text2table(x); // store text of each patient file into pdash.data.patient[i].txt
			// add cancerLabel
			var dlb = url.match(/_([^\_]+)\.txt/)[1];
			pdash.data.patient[i].columns.unshift('cancerLabel');
			pdash.data.patient[i].rows=pdash.data.patient[i].rows.map(function(ri){ri.unshift(dlb);return ri});
			count++;
			pdash.msg('loading table #'+count+'/'+n+': ['+pdash.data.patientTablesUrls[i]+']');
			if(count==n){
				var c = 0; // count # of patients
				pdash.data.patient.map(function(p){c = c + p.rows.length});
				pdash.msg('Found '+c+' patients, creating consensus table for their clinical and demographic data ...');
				var pColumns = jmat.unique(jmat.catArray(pdash.data.patient.map(function(p){return p.columns})));
				//var prows=jmat.tableLookupExact(pdash.data.patient[0],"cancerLabel",".*",pColumns);
				//for(var j =1;j<pdash.data.patient.length;j++){
				//	prows.push(jmat.tableLookupExact(pdash.data.patient[j]zs,"cancerLabel",".*",pColumns))
				//}
				pdash.data.patientTable={
					columns:pColumns,
					rows:jmat.catArray(pdash.data.patient.map(function(p){var pl=jmat.tableLookup(p,"",".*",pColumns); return pl.rows}))
				};
				pdash.data.patientTable.rows = jmat.arrayfun(pdash.data.patientTable.rows,function(x){ // replace null vaues by "[Not Available]"
					if(x==null){return "[Not Available]"}
					else{return x}
				})
				pdash.msg('Found '+c+' patients, creating consensus table for their clinical and demographic data ... done !','green');
			}
		})
	});
	//TCGA.ui.toast.info('getting Patient Tables ...')
	pdash.msg('getting Patient Tables ...','blue');
	return 'getting Patient Tables ...';
	},
	
	//jmat.loadVar('jQuery',function(){jQuery.get('clinical_patient_gbm.txt',function(x){txt = x ;tt = jmat.text2table(txt);console.log('done')})})
};

pdash.start();



